<template>
  <div>
    <el-card style="height: 80px">
      <el-from :inline="true" class="from">
        <el-form-item label="职位搜索">
          <el-input v-model="inputWords" placeholder="请输入搜索职位关键字" />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="searchRoleName"
            :disabled="!inputWords"
            >搜索</el-button
          >
          <el-button
            type="primary"
            @click="layoutSetting.refresh = !layoutSetting.refresh"
            >重置</el-button
          >
        </el-form-item>
      </el-from>
    </el-card>
    <el-card style="margin: 20px 0">
      <el-button type="primary" icon="Plus" @click="addRole"
        >添加角色</el-button
      >
      <el-table border style="margin: 20px 0" :data="rolePositionArr">
        <el-table-column
          label="#"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="id"
          width="80px"
          align="center"
          prop="id"
        ></el-table-column>
        <el-table-column
          label="角色名称"
          align="center"
          prop="roleName"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="300px" align="center">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="User"
              @click="setPermissions(row)"
              >分配权限</el-button
            >
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateRole(row)"
              >编辑</el-button
            >
            <el-popconfirm
              :title="`你确定要删除${row.roleName}?`"
              width="200px"
              @confirm="removeRole(row.id)"
            >
              <template #reference>
                <el-button type="primary" size="small" icon="Delete"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 6, 9, 11]"
        background
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @change="getHasAllRolePosition"
      />
    </el-card>
    <!-- 对话框组件(添加｜修改职位静态搭建) -->
    <el-dialog v-model="show" :title="roleParams.id ? '修改职位' : '添加职位'">
      <main>
        <el-form :model="roleParams" :rules="rules" ref="myFormRef">
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="roleParams.roleName"
              placeholder="请填写角色名称"
              style="margin-right: 20px"
            />
          </el-form-item>
        </el-form>
      </main>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="show = false">取消</el-button>
          <el-button type="primary" @click="saveRole"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分配权限抽屉组件 -->
    <el-drawer v-model="drawerShow">
      <template #header>
        <h4>分配菜单与按钮的权限</h4>
      </template>
      <template #default>
        <!-- 树节点组件 -->
        <el-tree
          ref="myTreeRef"
          style="max-width: 600px"
          :data="roleMenuArr"
          show-checkbox
          node-key="id"
          :default-checked-keys="selectArr"
          default-expand-all
          :props="defaultProps"
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawerShow = !drawerShow">cancel</el-button>
          <el-button type="primary" @click="setPermissionsSave"
            >confirm</el-button
          >
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { defineOptions, ref, onMounted, watch, reactive, nextTick } from "vue";
defineOptions({
  name: "Role",
});
//引入API
import {
  reqAllRolePosition,
  reqAddOrUpdateRolePosition,
  reqRemoveRolePosition,
  reqRoleMenu,
  reqSetPermissions,
} from "@/api/acl/role";
//引入类型
import type { RoleUser } from "@/api/acl/user/type";
import type { MenuList } from "@/api/acl/role/type";
import useLayoutSettingStore from "@/store/modules/layoutSetting";
import { ElMessage } from "element-plus";
import { fa } from "element-plus/es/locales.mjs";
let layoutSetting = useLayoutSettingStore();
let currentPage = ref<number>(1); //当前页码
let pageSize = ref<number>(3); //当前页码数据量
let total = ref<number>(0); //总数据
let inputWords = ref<string>(""); //搜索按钮的关键词
let rolePositionArr = ref<RoleUser[]>([]); //储存角色职位的数据
let show = ref<boolean>(false); //对话框的显示与隐藏
let myFormRef = ref(); //获取表单实例
let drawerShow = ref<boolean>(false); //用于控制抽屉组件的显示与隐藏
//收集新增角色职位的参数
let roleParams = reactive<RoleUser>({
  roleName: "",
});
let roleMenuArr = ref<MenuList[]>([]); //用于保存角色获取菜单数据的数组
let selectArr = ref<number[]>([]); //用于保存已选权限的数组
let myTreeRef = ref(); //获取Tree实例
//children	指定子树为节点对象的某个属性值
//label	    指定节点标签为节点对象的某个属性值
const defaultProps = {
  children: "children",
  label: "name",
};
onMounted(() => {
  getHasAllRolePosition();
});
//获取已有全部角色职位的数据
const getHasAllRolePosition = async () => {
  let result = await reqAllRolePosition(
    currentPage.value,
    pageSize.value,
    inputWords.value
  );
  // console.log(result);
  if (result.code == 200) {
    rolePositionArr.value = result.data.records;
    total.value = result.data.total;
  }
};
//监听当前页码中下拉框的数据条数的变化
watch([pageSize], () => {
  currentPage.value = 1;
});
//搜索按钮的回调
const searchRoleName = () => {
  getHasAllRolePosition();
  inputWords.value = "";
};
//添加角色
const addRole = () => {
  //清空数据
  Object.assign(roleParams, {
    id: "",
    roleName: "",
  });
  //清除表单校验字段
  nextTick(() => {
    myFormRef.value.clearValidate();
  });
  // 打开对话框
  show.value = true;
};
//修改角色
const updateRole = (row: RoleUser) => {
  Object.assign(roleParams, row);
  //清除表单校验字段
  nextTick(() => {
    myFormRef.value.clearValidate();
  });
  // 打开对话框
  show.value = true;
};
//自定义校验规则
const validatorRoleName = (rule: any, value: any, callback: any) => {
  if (value.trim() != "") {
    callback();
  } else {
    callback(new Error("表单内容不能为空"));
  }
};
//新增｜修改 表单校验
let rules = reactive({
  roleName: [{ required: true, trigger: "blur", validator: validatorRoleName }],
});

//添加｜修改角色职位的确定按钮的回调
const saveRole = async () => {
  //表单校验全部通过在发请求
  await myFormRef.value.validate();
  let result = await reqAddOrUpdateRolePosition(roleParams);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: roleParams.id ? "修改成功" : "添加成功",
    });
    getHasAllRolePosition();
    show.value = false;
  } else {
    ElMessage({
      type: "error",
      message: roleParams.id ? "修改失败" : "添加失败",
    });
    show.value = false;
  }
};

//删除已有的角色职位
let removeRole = async (id: number) => {
  let result = await reqRemoveRolePosition(id);
  if (result.code == 200) {
    ElMessage({ type: "success", message: "删除成功" });
    getHasAllRolePosition();
  } else {
    ElMessage({ type: "error", message: "系统数据不能删除" });
  }
};

//分配权限
let setPermissions = async (row: RoleUser) => {
  Object.assign(roleParams, row);
  let result = await reqRoleMenu(roleParams.id as number);
  if (result.code == 200) {
    roleMenuArr.value = result.data;
    // 遍历递归 保存所选权限的ID
    selectArr.value = filterSelectPermissions(roleMenuArr.value, []);
    drawerShow.value = true;
  }
};
// 遍历递归 保存所选权限的ID
let filterSelectPermissions = (roleMenuArr: MenuList[], initArr: number[]) => {
  roleMenuArr.filter((item) => {
    if (item.select && item.level == 4) {
      initArr.push(item.id as number);
    }
    if (item.children && item.children.length > 0) {
      filterSelectPermissions(item.children, initArr);
    }
  });
  return initArr;
};
//分配权限的确定按钮
let setPermissionsSave = async () => {
  let roleId = roleParams.id as number;
  //返回目前半选中的节点的 key 所组成的数组
  let halfSelect = myTreeRef.value.getHalfCheckedKeys();
  //返回当前选中节点 key 的数组
  let currentSelect = myTreeRef.value.getCheckedKeys();
  //合并数组
  let permissionId = halfSelect.concat(currentSelect);
  // 下发权限
  let result = await reqSetPermissions(roleId, permissionId);
  if (result.code == 200) {
    //关闭抽屉组件
    drawerShow.value = false;
    ElMessage({ type: "success", message: "权限分配成功" });
    //刷新页面
    window.location.reload();
  }
};
</script>

<style scoped lang="scss">
.from {
  display: flex;
  justify-content: space-between;
}
</style>
